package org.irri.smta.service.impl;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.irri.smta.domain.Role;
import org.irri.smta.domain.User;
import org.irri.smta.repository.IRoleRepository;
import org.irri.smta.repository.IUserRepository;
import org.irri.smta.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Named("userService")
@Transactional(readOnly = true)
public class UserService implements IUserService<User, Long> {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(UserService.class);

	@Inject
	@Named("userRepository")
	private IUserRepository userRepository;

	@Inject
	@Named("roleRepository")
	private IRoleRepository roleRepository;

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public User create(User user) {
		LOGGER.debug("User create(User user):" + user);
		Date now = new Date();
		user.setCreatedDate(now);
		user.setUpdatedDate(now);
		
		Role role = roleRepository.findOne(user.getRole().getId());
		user.setRole(role);
		
		LOGGER.debug("Creating a new user with information: " + user);
		return userRepository.save(user);
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public User update(User user) throws Exception {
		LOGGER.debug("User update(User user): " + user);
		user.setUpdatedDate(new Date());
		LOGGER.debug("Updating user with information: " + user);

		User userDb = userRepository.findOne(user.getId());

		if (userDb == null) {
			LOGGER.debug("No user found with id: " + user.getId());
			throw new Exception();
		}

		userRepository.save(user);
		return user;
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public User delete(Long id) throws Exception {
		LOGGER.debug("User delete(Long id): " + id);

		User user = userRepository.findOne(id);

		if (user == null) {
			LOGGER.debug("No user found with id: " + id);
			throw new Exception();
		}

		userRepository.delete(user);
		return user;
	}

	@Transactional(readOnly = true)
	@Override
	public User findById(Long id) {
		LOGGER.debug("User findById(Long id): " + id);
		return userRepository.findOne(id);
	}

	@Transactional(readOnly = true)
	@Override
	public List<User> findAll() {
		LOGGER.debug("List<User> findAll()");
		return userRepository.findAll();
	}

	@Transactional(readOnly = true)
	@Override
	public List<User> findAllOrdered() {
		LOGGER.debug("List<User> findAllOrdered()");
		return userRepository.findAllOrdered();
	}

	@Override
	public List<User> findByUsernameAndPassword(String username, String password) {
		LOGGER.debug("List<User> findByUsernameAndPassword(String username, String password): " + username);
		return userRepository.findByUsernameAndPassword(username, password);
	}

}
